<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>

    <style>
        .qrcode-img {
            /*width: 200px;*/
            /*height: 200px;*/
        }

        .qrcode-warp{
            text-align: center;
        }
    </style>
</head>

<body>
<h1>首页</h1>
<hr>
<h2>app/h5扫码登录</h2>
<div class="qrcode-warp">
    <img class="qrcode-img" src=""/>
    <input hidden="hidden" id="token" />
    <button class="qrcode-refresh">刷新二维码</button>
</div>
<hr>

</body>
</html>

<script type="text/javascript" src="/static/js/jquery-3.1.1.min.js"></script>
<script type="text/javascript">


    $(document).ready(function () {

        //请求生成二维码
        function requestQrcode(){
            return new Promise((resolve, reject)=>{

                $.ajax({
                    type: 'GET', // 请求的方式
                    headers: {"Request-Type": "ajax"},
                    url: '/index/scanQrcodeLogin/qrcode',  // 请求的 URL 地址
                    success: function (res, textStatus, xhr) { // 请求成功之后的回调函数
                        resolve(res);
                    }
                });

            })
        }

        /**
         * 操作生成或者刷新二维码
         */
        function handleQrcode() {
            requestQrcode().then(res => {
                if (res.code != 200) {
                    alert(res.message);
                    return;
                }
                if (res.code == 200) {
                    $(".qrcode-img").attr("src", 'data:image/jpg;base64,' + res.data.qrcodeBytes);
                    $("#token").val(res.data.token);
                    return;
                }

            })
        }


        handleQrcode();
        //刷新二维码
        $(".qrcode-refresh").click(function (){
           handleQrcode();

        })

        //轮询获取二维码状态
        var interval = setInterval(function (){

            // if(true){
            //     clearInterval(interval)
            //     return
            // }

            var token = $("#token").val();
            if(token != ''){
                $.ajax({
                    type: 'GET', // 请求的方式
                    url: '/index/scanQrcodeLogin/getQrCodeStatus',  // 请求的 URL 地址
                    headers: {"Request-Type": "ajax"},
                    // headers: {"Authorization": "Bearer " + localStorage.getItem("token")},
                    data: {token},
                    success: function (res, textStatus, xhr) { // 请求成功之后的回调函数

                        if (res.code != 200) {
                            // alert(res.message);
                            console.log(res.message)
                            return;
                        }
                        if (res.code == 200) {

                            //已确认
                            if(res.data.statusCode == 30000){

                                console.log("----------登录用户信息----------："+ res.data.userInfo.username)
                                // $("#accessToken").text(res.data.accessToken);
                                clearInterval(interval);
                                alert("登录成功")

                                localStorage.setItem("accessToken", res.data.accessToken)
                                window.location.href = "user.html";
                                return;
                            }

                            //已取消
                            if(res.data.statusCode == 50000){
                                // clearInterval(interval);
                                $(".qrcode-refresh").trigger("click");
                                alert("登录已取消")
                                return;
                            }
                        }


                    }
                });
            }
        }, 2000);

    })


    /**
     * 获取指定的URL参数值
     * URL:http://www.xxx.com/index?name=123
     * 参数：param URL参数
     * 调用方法:getParam("name")
     * 返回值:123
     * alert(getParam('date'));
     */
    function getParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        //search,查询？后面的参数，并匹配正则
        var r = location.search.substr(1).match(reg);
        if (r != null) return decodeURI(decodeURI(r[2]));
    }


    /**
     * 删除url上指定参数，并发起请求
     * window.location.replace(urlDelParams('params'))
     * @param name
     * @return {string}
     */
    function urlDelParams(name) {
        var loca = window.location
        var baseUrl = loca.origin + loca.pathname + '?'
        var query = loca.search.substr(1)
        if (query.indexOf(name) > -1) {
            var obj = {}
            var arr = query.split('&')
            for (var i = 0; i < arr.length; i++) {
                arr[i] = arr[i].split('=')
                obj[arr[i][0]] = arr[i][1]
            }
            delete obj[name]
            var url =
                baseUrl +
                JSON.stringify(obj)
                    .replace(/[\"\{\}]/g, '')
                    .replace(/\:/g, '=')
                    .replace(/\,/g, '&')
            return url
        }
    }

</script>